<template>
  <div>
    <div style="border-bottom: 1px solid #ebeef5; margin: 2px;">
      <el-row style="font-size: 14px; ">
        <el-col :span="12">
          <el-button-group>
            <el-tooltip :open-delay="500" content="新建根目录" placement="top">
              <el-button icon="el-icon-folder-add" size="mini" type="primary" @click="addCatalog(null)" />
            </el-tooltip>
            <el-tooltip :content="`新建${eTitle}`" :open-delay="500" placement="top">
              <el-button icon="el-icon-document-add" size="mini" type="primary" @click="addElement(0)" />
            </el-tooltip>
            <!--            <el-tooltip :open-delay="500" content="搜索" placement="top">-->
            <!--              <el-button size="mini" type="primary" @click="handleClickSearch"><svg-icon icon-class="search" /></el-button>-->
            <!--            </el-tooltip>-->
          </el-button-group>
          <el-tooltip :open-delay="500" content="用例编写状态" placement="top">
            <el-select v-model="treeFilter.editStatus" clearable placeholder="请选择用例编写状态" size="mini" style="margin-left: 2px; width: 110px;">
              <el-option v-for="item in editStatusOptions" :key="item.value" :label="item.name" :value="item.value" />
            </el-select>
          </el-tooltip>
          <el-tooltip :open-delay="500" content="优先级" placement="top">
            <el-select v-model="treeFilter.priority" clearable placeholder="请选择优先级" size="mini" style="margin-left: 2px; width: 65px;">
              <el-option v-for="item in priorityOptions" :key="item.value" :label="item.name" :value="item.value" />
            </el-select>
          </el-tooltip>
        </el-col>
        <el-col v-if="caseType === 3" :offset="6" :span="3">
          <div style="display: flex;">
            <div style="flex-grow: 1;">
              <el-tooltip :open-delay="500" content="可选运行环境，如果选择了运行环境，将使用此运行环境运行脚本" effect="dark" placement="top">
                <el-select v-model="debugEnv" clearable filterable placeholder="请选择环境" size="mini" style="width: 100%;" value-key="id">
                  <el-option v-for="item in envOptions" :key="item.id" :label="item.envName" :value="item.envName" />
                </el-select>
              </el-tooltip>
            </div>
            <div style="width: 2px;" />
          </div>
        </el-col>
        <el-col v-if="caseType === 3" :span="3">
          <div style="display: flex;">
            <div style="flex-grow: 1;">
              <el-tooltip :open-delay="500" effect="dark" placement="top">
                <div slot="content">自动选择 Agent，会自动选择一个在线的 Agent 运行脚本<br>自动选择的 Agent 有可能不能访问内网，这时就需要指定内网中的 Agent</div>
                <el-select v-model="debugAgentId" filterable placeholder="请选择 Agent" size="mini" style="width: 100%;" value-key="id">
                  <el-option v-for="item in agentOptions" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
              </el-tooltip>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
    <splitpanes style="height: 87vh">
      <pane :min-size="10" :size="30">
        <div style="width: 100%; height: 100%;">
          <div id="leftDiv" style="overflow-y: scroll; height: 100%;">
            <tree-component
              ref="treeComponent"
              :element-label="eTitle"
              catalog-label="目录"
              draggable
              lazy
              @tree-content="treeContent"
              @tree-sort="treeSort"
              @choose-catalog="chooseCatalog"
              @reload-catalog="reloadCatalog"
              @copy-catalog="copyCatalog"
              @add-catalog="addCatalog"
              @delete-catalog="deleteCatalog"
              @choose-element="chooseElement"
              @add-element="addElement"
              @copy-element="copyElement"
              @delete-element="deleteElement"
            />
          </div>
        </div>
      </pane>
      <pane :min-size="20" :size="70">
        <div id="rightDiv" style="overflow-y: scroll; width: 100%; height: 98%;">
          <el-tabs v-if="activeName" v-model="activeName" style="width: 100%;" type="border-card">
            <el-tab-pane v-if="activeName === 'catalog'" label="目录" name="catalog">
              <catalog-component
                ref="catalogComponent"
                :catalog-info="catalog"
                :type="eType"
                @create="createCatalog"
                @update="updateCatalog"
              />
            </el-tab-pane>
            <el-tab-pane v-if="activeName === 'element'" :label="eTitle" name="element">
              <test-script-component
                ref="testCaseComponent"
                v-model="testCaseVModelValue"
                :debug-agent-id="debugAgentId"
                :debug-env="debugEnv"
                @create="createElement"
                @next="nextElement"
                @update="updateElement"
                @updateNext="updateNextElement"
              />
            </el-tab-pane>
          </el-tabs>
        </div>
      </pane>
    </splitpanes>

    <!--    <el-dialog :visible.sync="searchDialogFormVisible" title="搜索" width="1200px" :close-on-click-modal="false">-->
    <!--      <test-case-search-component-->
    <!--        ref="testCaseSearchComponent"-->
    <!--        :type="caseType"-->
    <!--        @dblclickResultRow="dblclickResultRow"-->
    <!--      />-->
    <!--    </el-dialog>-->
  </div>
</template>

<style>
.splitpanes__pane {
  justify-content: flex-start;
  align-items: flex-start;
  display: flex;
  border: 1px solid #ebeef5;
}
.splitpanes__splitter {
  width: 5px;
  margin-left: -1px
}
#leftDiv::-webkit-scrollbar, #rightDiv::-webkit-scrollbar {
  width: 0px;
}
</style>

<script>
import { Pane, Splitpanes } from 'splitpanes'
import 'splitpanes/dist/splitpanes.css'
import TreeComponent from '@/components/functional_test/Tree/index.vue'
import CatalogComponent from '@/components/functional_test/Catalog/index.vue'
import TestScriptComponent from '@/components/performance_test/test_script/index.vue'
// import TestCaseSearchComponent from '@/components/functional_test/Search/testCaseSearch.vue'
import { copy as catalogCopy, del as catalogDel, listTreeContent, treeSort, getElementParent } from '@/api/functional_test/catalog'
import { testScriptDel } from '@/api/performance_test/test_script'
import preventBack from 'vue-prevent-browser-back'
import { selectAll as agent_selectAll } from '@/api/functional_test/agent'
import { findList as env_selectAll } from '@/api/functional_test/env_param'
import { editStatusOptions } from '@/enum/editStatus.js'
import { priorityOptions } from '@/enum/priority.js'
import { getCatalogTypeValue } from '@/enum/catalogType.js'

export default {
  // components: { Splitpanes, Pane, TreeComponent, CatalogComponent, TestScriptComponent, TestCaseSearchComponent },
  components: { Splitpanes, Pane, TreeComponent, CatalogComponent, TestScriptComponent },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  mixins: [preventBack], // 注入 阻止返回上一页
  props: {
    caseType: {
      type: Number,
      default: 1
    }
  },
  data() {
    return {
      editStatusOptions, // 编写状态 options
      priorityOptions, // 优先级 options
      treeFilter: { // tree 过滤条件
        editStatus: '',
        priority: ''
      },
      searchDialogFormVisible: false,
      eType: getCatalogTypeValue('性能测试用例'),
      eTitle: '测试脚本',
      activeName: null, // 当前激活的 tab 名称
      currentCatalogId: 0, // 当前选中的 catalog ID
      catalog: {}, // catalog 对象
      // 动态绑定到 testcase 组件中的数据
      testCaseVModelValue: {
        catalogId: 0,
        textMode: false
      },
      debugAgentId: 0, // 调试使用的代理
      debugEnv: '', // 调试使用的环境
      agentOptions: [],
      envOptions: []
      // testCaseComponentKey: 0 // 测试用例组件 key，用来刷新测试用例组件数据
    }
  },
  watch: {
    // 变量 currentCatalogId 的值变化后回调此方法
    currentCatalogId(catalogId) {
      this.testCaseVModelValue.catalogId = catalogId
    },
    // tree 过滤条件变化时候调用此方法
    treeFilter: {
      handler(value) {
        this.$refs.treeComponent.filter(value)
      },
      deep: true
    }
  },
  created() {
    this.agentSelectAll() // 获取所有 agent
    this.envSelectAll() // 获取所有 env
  },
  methods: {
    // tree：装载当前树节点数据
    treeContent(parentId, resolve) {
      listTreeContent({
        projectId: this.$store.getters.projectId,
        type: this.eType,
        parentId: parentId
      }).then(response => {
        resolve(response.data)
        this.$refs.treeComponent.filter(this.treeFilter) // 懒加载 tree 数据时，调用 filter 方法过滤数据
        this.chooseTestCase()
      })
    },
    // tree：拖拽排序
    treeSort(draggingNode, dropNode, dropType) {
      treeSort(this.$store.getters.projectId, this.eType, draggingNode.data, dropNode.data, dropType).then(response => {
        this.$message({ message: '修改排序成功!', type: 'success' })
      })
    },
    // tree：点击一个分类后调用此方法
    chooseCatalog(id) {
      this.activeName = 'catalog' // 设置当前 tab catalog
      this.currentCatalogId = this.catalog.id
      this.$nextTick(() => {
        this.$refs.catalogComponent.loadData(id)
      })
    },
    // tree：点击刷新一个分类的按钮后回调此方法
    reloadCatalog() {
      this.activeName = null // 清除 tab activeName
    },
    // tree：点击复制一个分类后调此方法
    copyCatalog(id, resolve) {
      catalogCopy(this.eType, this.$store.getters.projectId, id).then(response => {
        resolve(response.data)
      })
    },
    // tree：点击添加一个分类后调此方法
    addCatalog(parent_id) {
      this.activeName = 'catalog' // 设置当前 tab catalog
      this.$nextTick(() => {
        this.$refs.catalogComponent.add(parent_id)
      })
    },
    // tree：分类添加成功后回调此方法
    createCatalog(catalogInfo) {
      this.catalog = catalogInfo
      this.$refs.treeComponent.appendNode(catalogInfo.id, catalogInfo.parentId, catalogInfo.name, true, null, null)
    },
    // tree：分类修改成功后回调此方法
    updateCatalog(catalogInfo) {
      this.catalog = catalogInfo
      this.$refs.treeComponent.updateNode(catalogInfo)
    },
    // tree：删除一个分类
    deleteCatalog(id, resolve) {
      catalogDel(this.$store.getters.projectId, this.eType, id).then(response => {
        resolve()
        this.activeName = null // 清除 tab activeName
      })
    },
    // tree：点击一个元素后调用此方法
    chooseElement(id) {
      this.activeName = 'element' // 设置当前 tab element
      // this.testCaseComponentKey = this.testCaseComponentKey + 1 // 增加测试用例组件 key，强制刷新组件数据
      this.$nextTick(() => {
        this.$refs.testCaseComponent.loadData(id, this.eType)
      })
    },
    // tree：点击添加一个元素后调此方法
    addElement(parent_id) {
      this.currentCatalogId = parent_id
      this.activeName = 'element' // 设置当前 tab element
      // this.testCaseComponentKey = this.testCaseComponentKey + 1 // 增加测试用例组件 key，强制刷新组件数据
      this.$nextTick(() => {
        this.$refs.testCaseComponent.add(this.caseType)
      })
    },
    // tree：点击复制一个元素后调此方法
    copyElement(parent_id, id) {
      this.currentCatalogId = parent_id
      this.activeName = 'element' // 设置当前 tab element
      // this.testCaseComponentKey = this.testCaseComponentKey + 1 // 增加测试用例组件 key，强制刷新组件数据
      this.$nextTick(() => {
        this.$refs.testCaseComponent.copy(id)
        this.$message({ type: 'success', message: '复制成功!' })
      })
    },
    // tree：测试用例添加成功后回调此方法
    createElement(elementInfo) {
      this.$refs.treeComponent.appendNode(elementInfo.id, elementInfo.catalogId, elementInfo.name, false, elementInfo.priority, elementInfo.editStatus)
    },
    // tree：测试用例修改成功后回调此方法
    updateElement(elementInfo) {
      this.$refs.treeComponent.updateNode(elementInfo)
    },
    // tree：测试用例修改并继续成功后回调此方法
    updateNextElement(elementInfo) {
      this.$refs.treeComponent.updateNextNode(elementInfo.name)
    },
    // tree 点击 next 成功后回调此方法
    nextElement() {
      this.$refs.treeComponent.nextNode()
    },
    // tree：删除一个元素
    deleteElement(id, resolve) {
      testScriptDel(id).then(response => { // 这里要改成 delElement
        resolve()
        this.activeName = null // 清除 tab activeName
      })
    },
    // // 单击搜索按钮
    // handleClickSearch() {
    //   this.searchDialogFormVisible = true
    // },
    // // 双击搜索结果行
    // dblclickResultRow(elementParent) {
    //   this.searchDialogFormVisible = false
    //   this.$refs.treeComponent.setCurrentNode(elementParent)
    // },
    // 返回所有 agent
    agentSelectAll() {
      agent_selectAll().then(response => {
        this.agentOptions = [{ 'id': 0, 'name': '自动选择 Agent' }].concat(response.data)
      })
    },
    // 返回所有 env
    envSelectAll() {
      env_selectAll({ projectId: this.$store.getters.projectId }).then(response => {
        this.envOptions = response.data
      })
    },
    // 根据 url 参数，自动打开对应的 性能测试脚本
    chooseTestCase() {
      const id = this.$route.query.id
      if (id) {
        getElementParent({ type: 1, id: id }).then(response => {
          this.$nextTick(() => {
            this.$refs.treeComponent.setCurrentNode(response.data)
          })
        })
        this.chooseElement(id)
      }
    }
  }
}
</script>
